﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraSplashScreen;
using System.IO;

namespace DevExpress.MailClient.Win.Forms
{
    public partial class frmWorkFlowDecesinoMaking : PRO_DOCS.BLL.WIN.Templates.DevxPermissionTemplate
    {
        private PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_WORKFLOW CURRENT_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_INSTANCE;


        List<string> CURRENT_ARCHIVES_COPYING_FOLDERS
        {
            get;
            set;
        }

        public frmWorkFlowDecesinoMaking()
        {
            InitializeComponent();
        }

        public frmWorkFlowDecesinoMaking(PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_WORKFLOW _cURRENT_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_INSTANCE)
        {
            InitializeComponent();

            CURRENT_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_INSTANCE = _cURRENT_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_INSTANCE;
            this.Text = string.Format(this.Text, CURRENT_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_INSTANCE.APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_NAME);
            memoRequestDetails.Text = CURRENT_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_INSTANCE.APPLICATION_WORKFLOW_STEP.APPLICATION_WORKFLOW_STEP_DESCRIPTION;

            txtCreationDate.Text = DateTime.Now.ToLongDateString();
            txtCreatedBy.Text = PRO_DOCS.BLL.WIN.Authentication.LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.EMPLOYEE_FULL_NAME;

            PRO_DOCS.BLL.WIN.SystemSettings.SystemSettings systemSetting = new PRO_DOCS.BLL.WIN.SystemSettings.SystemSettings();
            CURRENT_ARCHIVES_COPYING_FOLDERS = systemSetting.APPLICATION_WORKFLOW_SAVING_FOLDERS;
        }

        private void btnApproveRejectRequest_Click(object sender, EventArgs e)
        {
            dxErrorProvider1.ClearErrors();

            if (!string.IsNullOrEmpty(memoRequestReply.Text))
            {
                CURRENT_SELECTED_ACTION = (TasksManager.TasksManagerViewer.WORKFLOW_ACTIONS)Convert.ToInt32(((XtraEditors.SimpleButton)(sender)).Tag.ToString());

                bgWorker_DoWork();

                if (workFlowStepAdded)
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            else
            {
                dxErrorProvider1.SetError(memoRequestReply, PRO_DOCS.BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Decesion Reason"));
            }
        }

        public Guid SET_FILE_WORKFLOW_ACTION()
        {
            Guid aRCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ID = Guid.NewGuid();
            PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOGSInsert
                (
                    aRCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ID,
                    CURRENT_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_INSTANCE.APPLICATION_WORKFLOW_INSTANCE_ID,
                    PRO_DOCS.BLL.WIN.Authentication.LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.LOGIN_USER_ID,
                    Convert.ToInt32(CURRENT_SELECTED_ACTION),
                    DECESION_REPLY_MESSAGE,
                    CURRENT_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_INSTANCE.APPLICATION_WORKFLOW_INSTANCE_NEXT_STEP_ID.Value
                );
            return aRCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ID;
        }
        public TasksManager.TasksManagerViewer.WORKFLOW_ACTIONS CURRENT_SELECTED_ACTION { get; set; }

        public string DECESION_REPLY_MESSAGE
        {
            get
            {
                return memoRequestReply.Text;
            }
        }

        private FileInfo selectedFileInfo
        { get; set; }

        bool workFlowStepAdded
        { get; set; }
        private void bgWorker_DoWork()
        {

            SplashScreenManager.ShowForm(typeof(DevExpress.MailClient.Win.Forms.wfMain), true, true);
            string errorMessage = string.Empty;
            string imageKey = string.Empty;
            btnApproveRequest.Invoke(new MethodInvoker(delegate
            {
                btnApproveRequest.Text = "Close";
            }));

            {
                List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT> log_attachments = new List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT>();

                gridControl1.Invoke(new MethodInvoker(delegate
                {
                    for (int i = 0; i < gridView1.DataRowCount; i++)
                    {
                        gridView1.SetRowCellValue(i, gcCurrentStatus, "progress");
                        DevExpress.MailClient.Win.Data.UploadedPhysicalFiles uploadedPhysicalFiles = gridView1.GetRow(i) as DevExpress.MailClient.Win.Data.UploadedPhysicalFiles;


                        bool fileUploaded = false;
                        //1. Copy the file to the Folder
                        if (uploadedPhysicalFiles.CheckedFile)
                        {
                            //the new fileId to be named with
                            string newCreatedPhysicalFileName = uploadedPhysicalFiles.FileId.ToString();
                            //the original file path
                            FileInfo currentConsumedFile = uploadedPhysicalFiles.FileInfo;
                            //a. copy the file

                            for (int fc = 0; fc < CURRENT_ARCHIVES_COPYING_FOLDERS.Count; fc++)
                            {
                                try
                                {
                                    currentConsumedFile.CopyTo(Path.Combine(CURRENT_ARCHIVES_COPYING_FOLDERS[fc], newCreatedPhysicalFileName), true);
                                    fileUploaded = true;
                                    break;
                                }
                                catch (Exception ex)
                                {
                                    gridView1.SetRowCellValue(i, gcMessage, ex.Message);
                                }
                            }

                            if (fileUploaded)
                            {
                                PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT single_log_attachment = new PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT();
                                single_log_attachment.ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT_ID = uploadedPhysicalFiles.FileId;
                                single_log_attachment.ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT_NAME = uploadedPhysicalFiles.FileInfo.Name;
                                single_log_attachment.ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT_PHYSICAL_NAME = newCreatedPhysicalFileName;

                                log_attachments.Add(single_log_attachment);
                                gridView1.SetRowCellValue(i, gcCurrentStatus, "done");
                            }
                            else
                            {

                                gridView1.SetRowCellValue(i, gcMessage, "There was error copying the file to the destination folder, please make sure that there is enough desk space or you are connected the network path successfully.");
                                gridView1.SetRowCellValue(i, gcCurrentStatus, "alert");
                            }

                        }
                        else
                        {
                            gridView1.SetRowCellValue(i, gcCurrentStatus, "removed");
                        }

                        if (fileUploaded)
                            Succeded++;
                        else
                            Error++;
                    }

                }));

                if (Error.Equals(0))
                {
                    //1. ADD the Workflow step
                    Guid aDDED_WORKFLOW_STEP_LOG_ID = SET_FILE_WORKFLOW_ACTION();
                    for (int i = 0; i < log_attachments.Count; i++)
                    {
                        //2. ADD the Workflow step Attachment
                        PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENTSInsert
                            (
                               log_attachments[i].ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT_ID,
                               aDDED_WORKFLOW_STEP_LOG_ID,
                               log_attachments[i].ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT_NAME,
                               log_attachments[i].ARCHIVE_DEPARTMENT_FILE_WORKFLOW_LOG_ATTACHMENT_PHYSICAL_NAME
                            );
                    }

                    workFlowStepAdded = true;
                }
            }

            SplashScreenManager.CloseForm();
        }

        private int Succeded
        {
            get;
            set;
        }


        private int Error
        {
            get;
            set;
        }

        private void tsbAddStepAttachmnets_Click(object sender, EventArgs e)
        {

            List<DevExpress.MailClient.Win.Data.UploadedPhysicalFiles> selectedFilePathes = new List<DevExpress.MailClient.Win.Data.UploadedPhysicalFiles>();

            OpenFileDialog openFileDialogObj = new OpenFileDialog();
            openFileDialogObj.Title = "Choose Department Files.";
            openFileDialogObj.Multiselect = true;
            openFileDialogObj.FilterIndex = 1;
            openFileDialogObj.RestoreDirectory = true;
            if (openFileDialogObj.ShowDialog() == DialogResult.OK)
            {
                gridControl1.DataSource = null;


                string[] selectedFiles = openFileDialogObj.FileNames;



                for (int i = 0; i < selectedFiles.Length; i++)
                {
                    string fullDownloadReportPath = selectedFiles[i];
                    selectedFileInfo = new FileInfo(fullDownloadReportPath);

                    DevExpress.MailClient.Win.Data.UploadedPhysicalFiles single_uploaded_physical_file = new DevExpress.MailClient.Win.Data.UploadedPhysicalFiles();
                    single_uploaded_physical_file.CheckedFile = true;
                    single_uploaded_physical_file.FileId = Guid.NewGuid();
                    single_uploaded_physical_file.FileInfo = selectedFileInfo;
                    single_uploaded_physical_file.UploadingMessage = string.Empty;
                    single_uploaded_physical_file.CurrentIcon = "none";
                    selectedFilePathes.Add(single_uploaded_physical_file);
                }

                gridControl1.DataSource = selectedFilePathes;
            }
        }

        private void tsbDeleteFile_Click(object sender, EventArgs e)
        {
            gridView1.DeleteSelectedRows();
        }
    }
}